﻿using Cloud.Update.Core.Models;
using Cloud.Update.Core.Utils;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;

namespace Cloud.Update
{
    /// <summary>
    /// App.xaml 的交互逻辑
    /// </summary>
    public partial class App : Application
    {
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);
        System.Threading.Mutex mutex;

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            Current.DispatcherUnhandledException += new System.Windows.Threading.DispatcherUnhandledExceptionEventHandler(App_DispatcherUnhandledException);
            AppDomain.CurrentDomain.UnhandledException +=  new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            #region 只能运行一个
            bool ret; 
            mutex = new System.Threading.Mutex(true, "Cloud.Update", out ret);
            if (!ret)
            {
                //如果存在 那么就打开存在的程序
                //获取程序名称
                string pName = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name.ToString();
                Process[] temp = Process.GetProcessesByName(pName);//在所有已启动的进程中查找需要的进程；     
                if (temp.Length > 0)//如果查找到     
                {
                    IntPtr handle = temp[0].MainWindowHandle;
                    SwitchToThisWindow(handle, true);    // 激活，显示在最前 
                    System.Threading.Thread.Sleep(500);//睡眠500毫秒 然后关闭本程序
                }
                Environment.Exit(0);
            }
            #endregion

           
            ClientParameter clientParameter = null;
            DirectoryInfo directInfo = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);//获取文件

            //clientParameter = new ClientParameter
            //{
            //    IsRestore = true,
            //    BackUpPath = directInfo.Parent.FullName + "/backup/",
            //    AppName = directInfo.Parent.FullName + @"\current\Cloud.Test.Main.exe",
            //    UnZipPath = directInfo.Parent.FullName + @"\current\",//解压文件存放位置,可默认
            //};
            if (e.Args.Length > 0)//e.Args.Length > 0
            {
                var args = e.Args[0];
               // args = "eyJBcHBUeXBlIjoxLCJBcHBOYW1lIjoiQzpcXFVzZXJzX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WdhYmx6LW1hc3Rlci56aXAiLCJJc1VwZGF0ZSI6dHJ1ZX0seyJOYW1lIjpudWxsLCJWZXJzaW9uIjoiNSIsIlVybCI6Imh0dHA6Ly8xMjcuMC4wLjE6NTAwMC9FQ2hhcnRzU0RLLW1hc3Rlci56aXAiLCJJc1VwZGF0ZSI6dHJ1ZX0seyJOYW1lIjpudWxsLCJWZXJzaW9uIjoiNiIsIlVybCI6Imh0dHA6Ly8xMjcuMC4wLjE6NTAwMC9FQ2hhcnRzTmV0LW1hc3Rlci56aXAiLCJJc1VwZGF0ZSI6dHJ1ZX0seyJOYW1lIjpudWxsLCJWZXJzaW9uIjoiNyIsIlVybCI6Imh0dHA6Ly8xMjcuMC4wLjE6NTAwMC9IYW5keUNvbnRyb2wtbWFzdGVyLnppcCIsIklzVXBkYXRlIjp0cnVlfSx7Ik5hbWUiOm51bGwsIlZlcnNpb24iOiI4IiwiVXJsIjoiaHR0cDovLzEyNy4wLjAuMTo1MDAwL0xpdmUtQ2hhcnRzLW1hc3Rlci56aXAiLCJJc1VwZGF0ZSI6dHJ1ZX0seyJOYW1lIjpudWxsLCJWZXJzaW9uIjoiOSIsIlVybCI6Imh0dHA6Ly8xMjcuMC4wLjE6NTAwMC9tdnZtbGlnaHQtbWFzdGVyLnppcCIsIklzVXBkYXRlIjp0cnVlfV19";
                try
                {
                    clientParameter = SerializeUtil.Deserialize<ClientParameter>(args);
                    
                    Validate.ValidateClientParameter(clientParameter);
                }
                catch (Exception ex)
                {
                    var dialogResult = MessageBox.Show("更新错误,更新参数不正确,是否跳本次更新?\n错误信息:"+ AppDomain.CurrentDomain.BaseDirectory+"\n"+ex.Message, "更新参数传入错误", MessageBoxButton.OKCancel, MessageBoxImage.Error, MessageBoxResult.Yes, MessageBoxOptions.None);
                    if (dialogResult == MessageBoxResult.Cancel)
                    {
                        Process.GetCurrentProcess().Kill();
                    }
                    else {
                        //todo
                        //跳过本次更新的方式启动
                        try
                        {
                            var path = directInfo.Parent.FullName + @"\current\Cloud.Test.Main.exe";
                            if (File.Exists(path))
                            {
                                Process.Start(path, "jumpversion");
                            }
                        }
                        catch
                        {
                        }
                        finally
                        {
                            Process.GetCurrentProcess().Kill();
                        }
                    }
                }
            }
            else {
                
                var result = MessageBox.Show("更新程序不能直接运行,请先启动主程序,检查到有版本跟新后该程序会自动运行!", "错误的启动方式", MessageBoxButton.OK, MessageBoxImage.Warning);
                if (result == MessageBoxResult.OK || result == MessageBoxResult.Cancel) {
                    Process.GetCurrentProcess().Kill();
                }
                
            }
            MainWindow window = new MainWindow();
            window.DataContext = new MainViewModel(clientParameter);
            window.Show();

        }
        void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            try
            {
                if (e.ExceptionObject is System.Exception)
                {
                    Error(e.ExceptionObject as Exception);
                }
            }
            catch (Exception ex)
            {

                Error(ex);
            }
        }

        void App_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            try
            {
                Error(e.Exception);
                e.Handled = true;
            }
            catch (Exception ex)
            {
                Error(ex);
            }
        }

        void Error(Exception ex) {
            var dialogResult = MessageBox.Show("升级失败了,是否回到上一版本?\n错误信息:" + ex.ToString(), "程序意外中止", MessageBoxButton.OKCancel, MessageBoxImage.Error, MessageBoxResult.Yes);
            if (dialogResult == MessageBoxResult.Cancel)
            {
                Process.GetCurrentProcess().Kill();
            }
            else
            {
                //todo
                //回滚
            }
        }
    }
}
